const { prisma } = require('../config/prisma');
const crypto = require('crypto');
const { generateOrderNo, generatePayParams } = require('../services/payment.service');

/**
 * 获取会员类型对应的配置
 */
const getMemberConfig = (memberType) => {
  const configs = {
    1: { days: 7, amount: 9.9 },
    2: { days: 30, amount: 29.9 },
    3: { days: 365, amount: 299 }
  };
  return configs[memberType];
};

/**
 * 创建订单
 */
const createOrder = async (req, res) => {
  try {
    const { type, memberType, cardNo } = req.body;

    // 验证参数
    if (!type || !memberType || (type === 2 && !cardNo)) {
      return res.status(400).json({
        code: 400,
        message: '参数错误'
      });
    }

    // 验证会员类型
    const config = getMemberConfig(memberType);
    if (!config) {
      return res.status(400).json({
        code: 400,
        message: '无效的会员类型'
      });
    }

    // 如果是卡密兑换，先验证卡密
    let card;
    if (type === 2) {
      card = await prisma.card.findFirst({
        where: {
          cardNo: cardNo,
          status: 0 // 未使用
        }
      });

      if (!card) {
        return res.status(400).json({
          code: 400,
          message: '无效的卡密'
        });
      }

      if (card.memberType !== memberType) {
        return res.status(400).json({
          code: 400,
          message: '卡密类型与所选会员类型不匹配'
        });
      }
    }

    // 使用事务处理订单创建和卡密兑换
    const result = await prisma.$transaction(async (tx) => {
      // 创建订单
      const order = await tx.order.create({
        data: {
          user: {
            connect: {
              id: req.user.id
            }
          },
          orderNo: generateOrderNo(),
          amount: config.amount,
          memberType: memberType,
          days: config.days,
          type,
          status: 0,
          card: cardNo ? {
            connect: {
              cardNo
            }
          } : undefined
        },
        include: {
          user: true
        }
      });

      // 如果是卡密兑换，更新卡密状态和会员信息
      if (type === 2) {
        // 更新卡密状态
        await tx.card.update({
          where: { cardNo: cardNo },
          data: {
            status: 1,
            usedUserId: req.user.id,
            usedTime: new Date(),
            orderNo: order.orderNo
          }
        });

        // 更新会员信息
        const user = await tx.user.findUnique({
          where: { id: req.user.id }
        });

        const now = new Date();
        const newExpireTime = user.expireTime && user.expireTime > now
          ? new Date(user.expireTime.getTime() + config.days * 24 * 60 * 60 * 1000)
          : new Date(now.getTime() + config.days * 24 * 60 * 60 * 1000);

        await tx.user.update({
          where: { id: req.user.id },
          data: {
            memberType: memberType,
            expireTime: newExpireTime
          }
        });

        return {
          order,
          expireTime: newExpireTime
        };
      }

      return { order };
    }, {
      timeout: 10000 // 设置事务超时时间为10秒
    });

    // 返回响应
    if (type === 2) {
      return res.json({
        code: 200,
        data: {
          orderNo: result.order.orderNo,
          amount: result.order.amount,
          memberType: result.order.memberType,
          days: result.order.days,
          status: 1,
          expireTime: result.expireTime
        }
      });
    }

    // 如果是微信支付，生成支付参数
    const payParams = await generatePayParams(result.order);

    res.json({
      code: 200,
      data: {
        orderNo: result.order.orderNo,
        amount: result.order.amount,
        memberType: result.order.memberType,
        days: result.order.days,
        payParams: payParams
      }
    });
  } catch (error) {
    console.error('Create order error:', error);
    res.status(500).json({
      code: 500,
      message: '创建订单失败'
    });
  }
};

/**
 * 查询订单
 */
const queryOrder = async (req, res) => {
  try {
    const { order_no } = req.query;

    if (!order_no) {
      return res.status(400).json({
        code: 400,
        message: '订单号不能为空'
      });
    }

    // 查询订单
    const order = await prisma.order.findFirst({
      where: {
        orderNo: order_no,
        userId: req.user.id
      },
      select: {
        orderNo: true,
        status: true,
        memberType: true,
        amount: true,
        type: true,
        days: true,
        createdAt: true
      }
    });

    if (!order) {
      return res.status(404).json({
        code: 404,
        message: '订单不存在'
      });
    }

    res.json({
      code: 200,
      data: order
    });
  } catch (error) {
    console.error('Query order error:', error);
    res.status(500).json({
      code: 500,
      message: '查询订单失败'
    });
  }
};

const exchangeCard = async (req, res) => {
  try {
    const { card_no } = req.body;
    const userId = req.user.id;

    const card = await prisma.card.findUnique({
      where: { cardNo: card_no }
    });

    if (!card) {
      return res.status(400).json({
        code: 400,
        message: 'Invalid card number'
      });
    }

    if (card.status !== 0) {
      return res.status(400).json({
        code: 400,
        message: 'Card has been used'
      });
    }

    // Update card status
    await prisma.card.update({
      where: { cardNo: card_no },
      data: {
        status: 1,
        usedUserId: userId,
        usedTime: new Date()
      }
    });

    // Update user membership
    await updateMembership(userId, card.days);

    res.json({
      code: 0,
      data: {
        member_type: card.memberType,
        days: card.days,
        expire_time: await getUserExpireTime(userId)
      }
    });
  } catch (error) {
    console.error('Exchange card error:', error);
    res.status(500).json({
      code: 500,
      message: 'Failed to exchange card'
    });
  }
};

const handlePaymentNotify = async (req, res) => {
  try {
    const { orderNo, status } = req.body; // Simplified, actual params depend on payment provider

    if (status === 'SUCCESS') {
      const order = await prisma.order.findUnique({
        where: { orderNo }
      });

      if (!order || order.status !== 0) {
        return res.json({ code: 0, message: 'success' }); // Always return success to payment provider
      }

      // Update order status
      await prisma.order.update({
        where: { orderNo },
        data: {
          status: 1,
          payTime: new Date()
        }
      });

      // Update user membership
      await updateMembership(order.userId, order.days);
    }

    res.json({ code: 0, message: 'success' });
  } catch (error) {
    console.error('Payment notify error:', error);
    res.json({ code: 0, message: 'success' }); // Always return success to payment provider
  }
};

async function updateMembership(userId, days) {
  const user = await prisma.user.findUnique({
    where: { id: userId }
  });

  const now = new Date();
  const newExpireTime = user.expireTime && user.expireTime > now
    ? new Date(user.expireTime.getTime() + days * 24 * 60 * 60 * 1000)
    : new Date(now.getTime() + days * 24 * 60 * 60 * 1000);

  await prisma.user.update({
    where: { id: userId },
    data: {
      memberType: 1,
      expireTime: newExpireTime
    }
  });
}

async function getUserExpireTime(userId) {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { expireTime: true }
  });
  return user.expireTime;
}

module.exports = {
  createOrder,
  queryOrder,
  exchangeCard,
  handlePaymentNotify
}; 